package com.ruoyi.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author ab785
 * createTime: 2021-11-8.
 * description: 雪花算法获取工具类
 */
@Component
public class SnowFlakeUtils {

    /**
     * workerId
     */
    private long workerId = 0L;

    /**
     * 数据中心ID
     */
    private long centerId = 1L;

    /**
     * 雪花算法实体
     */
    private Snowflake snowflake = null;

    @PostConstruct
    public void init() {
        //TODO 分布式处理时需要修改workerId和centerId的生成算法
        this.workerId = 0L;
        this.centerId = 1L;
        this.snowflake = IdUtil.getSnowflake(workerId, centerId);
    }

    /**
     * 下一个ID
     */
    public synchronized long nextId() {
        return snowflake.nextId();
    }

    /**
     * 下一个ID  字符串形式
     */
    public synchronized String nextIdStr() {
        return snowflake.nextIdStr();
    }

    public long getWorkerId() {
        return workerId;
    }

    public void setWorkerId(long workerId) {
        this.workerId = workerId;
    }

    public long getCenterId() {
        return centerId;
    }

    public void setCenterId(long centerId) {
        this.centerId = centerId;
    }
}
